<?php
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;
use Common\ORG\Util\UploadFile;

/**
 * 政务内容管理
 * Class UserController
 * @package Admin\Controller
 */
class UserController extends BaseController {
    /**
     * 系统管理 -> 系统管理 -> 用户管理 -> listview
     */
    public function index(){
        //获取搜索条件
        $filter = $this->fn_GenerateFilter();
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();

        //分页信息
        $pageNum = intval(I("post.page"));
        $pageNum = $pageNum==0?1:$pageNum;
        $page = $this->fn_GetPageInfo($where, $pageNum);
        $this->assign("page", $page);

        //搜索出用户信息
        $limit = ($page['from']-1).",".$page['num'];
        $list = M("user")->where($where)->order($order)->limit($limit)->select();
        for($i=0; $i<count($list); $i++){
            $list[$i]["offset"] = $page['from']-1+$i;
        }
        $this->assign("list", $list);

        //company相关
        $company = $this->fn_GetCompany();
        $this->assign("company", $company);

        //role相关
        $role = $this->fn_GetRole();
        $this->assign("role", $role);

        //设置搜索条件
        $this->assign("filter", $filter);
        $this->display();
    }

    public function import(){
        if(IS_POST){
            $upload = new UploadFile();// 实例化上传类
            $upload->maxSize  = 314572811 ;// 设置附件上传大小
            $upload->allowExts  = array('xls', 'xlsx');// 设置附件上传类型
            $upload->savePath =  './Public/UPLOADS/';// 设置附件上传目录
            $info = $upload->uploadOne($_FILES["excel"]);

            if ($info['state']) {
                $newFile = $upload->savePath . $info["info"]['savename'];

                if(I("post.type")=="lzf"){
                    $this->action_ImportOldLzfData($newFile);
                }else if(I("post.type")=="zggf"){
                    $this->action_ImportOldZggfData($newFile);
                }else if(I("post.type")=="zlbt"){
                    $this->fn_ImportZlbtData($newFile);
                }
                $this->error("恭喜您，数据导入成功");
            }else{
                $this->error($info["msg"]);
            }
        }
        $this->display();
    }

    public function action_ImportOldZggfData($inputFileName){

        $fields = array("name" , "idno", "phone", "house", "house_type", "size", "zj",
            "2015zj", "2015yf", "2016zj", "2016yf", "2017zj", "2017yf", "remarks"
        );
        $data = $this->fn_ImportTaizhangExcel($inputFileName, $fields);
        $trans = M();
        $trans->startTrans();   // 开启事务
        try {
            $this->action_ImportZggfData($data);
            $trans->commit();   // 提交事务
        }catch (Exception $e) {
            $trans->rollback();   // 开启事务
            $this->error($e->getMessage());
        }
    }

    private function fn_GenerateMenmianNo($house_type){
        $data = array("time"=>date("Y-m-d H:i:s"));
        $no = M("menmian_no")->add($data);
        if($house_type=='商业用房'){
            return "S".$no;
        }else if($house_type=='直管公房'){
            return "Z".$no;
        }else{
            return null;
        }
    }

    private function action_ZggfImportApply($data, $index){
        $apply = array(
            "no" => $data["no"],
            "community" => $data["community"],
            "house_no" => $data["house_no"],
            "house_addr" => $data["house_addr"],
            "house_type" => $data["house_type"],
            "name" => $data["name"],
            "gender" => "男",
            "phone" => $data["phone"],
            "idno" => $data["idno"],
            "resident_num" => 0,
            "yj" => 0,
            "zj" => $data["zj"],
            "size" => $data["size"],
            "mzj" => $data["zj"],
            "remarks" => $data["remarks"],
            "cuser" => session("username"),
            "ctime" => date("Y/m/d"),
        );
        $res = M("menmian")->add($apply);
        if(!$res){
            $this->error(M("menmian")->getLastSql());
            $this->error("行：".($index+2).",创建直管公房申请失败");
        }
    }

    public function action_ImportOldLzfData($inputFileName){

        $fields = array("name" , "idno", "name2", "idno2",
            "phone", "resident_num", "dibaohm", "dibaork",
            "batch", "seq", "house", "size", "uzj", "zj",
            "2015zj", "2015yf", "2016zj", "2016yf", "2017zj", "2017yf",
        );
        $data = $this->fn_ImportTaizhangExcel($inputFileName, $fields);

        $lzfData = array();
        $gzfData = array();
        foreach($data as $item){
            if(intval($item['dibaork'])>0){
                $lzfData[] = $item;
            }else{
                $gzfData[] = $item;
            }
        }

        $trans = M();
        $trans->startTrans();   // 开启事务
        try {
            $this->action_ImportLzfData($lzfData);
            $this->action_ImportGzfData($gzfData);
            $trans->commit();   // 提交事务
        }catch (Exception $e) {
            $trans->rollback();   // 开启事务
            $this->error($e->getMessage());
        }
    }

    public function action_ImportZggfData($data){

        for($i=0; $i<count($data); $i++){
            //第一步：租金缴纳检查
            $zujin = $this->fn_FormatZujin($data[$i]);
            if(count($zujin)==0){
                //$this->error("行：".($i+2).", 没有缴纳租金");
            }

            //第三步：房源验证
            $house = M("house h")
                ->field("h.*, c.name as comm")
                ->where(array("h.addr"=>$data[$i]['house']))
                ->join(C("DB_PREFIX")."community c on c.id=h.community_id", "LEFT")
                ->find();
            if(!$house){
                //$this->error(M("house")->getLastSql());
                $this->error("行：".($i+2).",房源信息：".$data[$i]['house']."不存在");
            }else{
                $data[$i]['dibaork'] = 0;
                $data[$i]['resident_num'] = 1;
                $data[$i]['jtnum'] = 1;
                $data[$i]['name2'] = null;
                $data[$i]['idno2'] = null;
                $data[$i]['dbnum'] = null;
                $data[$i]['dibaohm'] = null;
                $data[$i]['house_no'] = $house['name'];
                $data[$i]['house_type'] = $house['type'];
                $data[$i]['house_zj'] = $house['price'];
                $data[$i]['house_mzj'] = $house['mprice'];
                $data[$i]['house_size'] = $house['size'];
                $data[$i]['house_addr'] = $house['addr'];
                $data[$i]['house_comm'] = $house['comm'];
                $data[$i]['community'] = $house['comm'];
            }

            //第二步：导入直管公房申请信息
            $data[$i]['no'] = $this->fn_GenerateMenmianNo($data[$i]['house_type']);
            $this->action_ZggfImportApply($data[$i], $i);

			//没有缴纳租金的情况，就不进行下一步
			if(count($zujin)==0){
                return true;
            }
			
            //第五步：新创建合同，并缴纳第一年的租金
            $this->action_ImportContact($data[$i], $zujin, $i, $data[$i]['house_type']);

            //第六步：缴纳所有年份的租金
            $this->action_ImportRental($data[$i], $zujin, $i, $data[$i]['house_type']);

            //第七步：修改房源状态
            $this->fn_MarkHouseOccupied($data[$i], $zujin[0], $i);

            //第八步：更新申请信息
            $this->fn_UpdateZggfApply($data[$i], $i);
        }
    }

    private function fn_UpdateZggfApply($data, $index){
        $info = array(
            "state" => "申请成功",
            "contact_no" => "HT".$data['no'],
            "contact_date" => date("Y/m/d"),
        );
        $res = M("menmian")->where(array("no"=>$data['no']))->save($info);
        if(!$res){
            $this->error("行：".($index+2).", 直管公房申请更新失败");
        }
    }

    public function action_ImportLzfData($data){

        for($i=0; $i<count($data); $i++){
            //第一步：租金缴纳检查
            $zujin = $this->fn_FormatZujin($data[$i]);
            if(count($zujin)==0){
                //$this->error("行：".($i+2).", 没有缴纳租金");
            }

            //第二步：导入廉租房申请信息
            $data[$i]['no'] = $this->fn_GenerateLzfNo();
            $this->action_LzfImportApply($data[$i], $zujin, $i);

            //第三步：房源验证
            $house = M("house h")
                ->field("h.*, c.name as comm")
                ->where(array("h.addr"=>$data[$i]['house']))
                ->join(C("DB_PREFIX")."community c on c.id=h.community_id", "LEFT")
                ->find();
            if(!$house){
                //$this->error(M("house")->getLastSql());
                $this->error("行：".($i+2).",房源信息：".$data[$i]['house']."不存在");
            }
            if($house['state']=='租赁中'){
                $this->error("行：".($i+2).",房源：".$data[$i]['house']."处于租赁状态中，不能办理入住手续");
            }else{
                $data[$i]['house_no'] = $house['name'];
                $data[$i]['house_zj'] = $house['price'];
                $data[$i]['house_mzj'] = $house['mprice'];
                $data[$i]['house_size'] = $house['size'];
                $data[$i]['house_addr'] = $house['addr'];
                $data[$i]['house_comm'] = $house['comm'];
            }

            //第四步：创建批次
            $lotId = $this->action_ImportLottery($data[$i], $i, count($zujin));

			//没有缴纳租金的情况，就不进行下一步
			if(count($zujin)==0){
                return true;
            }

            //第五步：新创建合同，并缴纳第一年的租金
            $this->action_ImportContact($data[$i], $zujin, $i, "廉租房");

            //第六步：缴纳所有年份的租金
            $this->action_ImportRental($data[$i], $zujin, $i, "廉租房");

            //第七步：修改房源状态
            $this->fn_MarkHouseOccupied($data[$i], $zujin[0], $i);

            //添加房源租赁记录
            /*$remarks = "实物配租";
            $res = $this->fn_AddHouseRentalLog($data[$i], $remarks);
            if (!$res) {
                $this->error("系统错误，房源租赁日志写入失败");
            }*/

            //第八步：更新申请信息
            $this->fn_UpdateLzfApply($data[$i], $i);
        }
    }

    public function action_ImportGzfData($data){
        for($i=0; $i<count($data); $i++){
            //第一步：租金缴纳检查
            $zujin = $this->fn_FormatZujin($data[$i]);
            if(count($zujin)==0){
                //$this->error("行：".($i+2).", 没有缴纳租金");
            }

            //第二步：导入廉租房申请信息
            $data[$i]['no'] = $this->fn_GenerateGzfNo();
            $this->action_GzfImportApply($data[$i], $zujin, $i);

            //第三步：房源验证
            $house = M("house h")
                ->field("h.*, c.name as comm")
                ->where(array("h.addr"=>$data[$i]['house']))
                ->join(C("DB_PREFIX")."community c on c.id=h.community_id", "LEFT")
                ->find();
            if(!$house){
                //$this->error(M("house")->getLastSql());
                $this->error("行：".($i+2).",房源信息：".$data[$i]['house']."不存在");
            }

            if($house['state']=='租赁中'){
                $this->error("行：".($i+2).",房源：".$data[$i]['house']."处于租赁状态中，不能办理入住手续");
            }else{
                $data[$i]['house_no'] = $house['name'];
                $data[$i]['house_zj'] = $house['price'];
                $data[$i]['house_mzj'] = $house['mprice'];
                $data[$i]['house_size'] = $house['size'];
                $data[$i]['house_addr'] = $house['addr'];
                $data[$i]['house_comm'] = $house['comm'];
            }

            //第四步：创建批次
            $this->action_ImportLottery($data[$i], $i, count($zujin));

			//没有缴纳租金的情况，就不进行下一步
			if(count($zujin)==0){
                return true;
            }
			
            //第五步：新创建合同，并缴纳第一年的租金
            $this->action_ImportContact($data[$i], $zujin, $i, "公租房");

            //第六步：缴纳所有年份的租金
            $this->action_ImportRental($data[$i], $zujin, $i, "公租房");

            //第七步：修改房源状态
            $this->fn_MarkHouseOccupied($data[$i], $zujin[0], $i);

            //添加房源租赁记录
            /*$remarks = "实物配租";
            $res = $this->fn_AddHouseRentalLog($data[$i], $remarks);
            if (!$res) {
                $this->error("系统错误，房源租赁日志写入失败");
            }*/

            //第八步：更新申请信息
            $this->fn_UpdateGzfApply($data[$i], $i);
        }
    }

    /**
     * 添加房源的租赁记录
     * @param $houseId 房源ID
     * @param $name 租赁人姓名
     * @param $idno 租赁人身份证
     */
    protected function fn_AddHouseRentalLog($data, $remarks){
        $rental = array(
            "type"=>"保障分房",
            "remarks"=> $remarks,
            "cuser"=> self::$u["username"],
            "ctime"=> date("Y/m/d"),
            "house_no"=> $data["house_no"],
            "bzdx"=> $data['name'],
            "idno"=> $data['idno'],
        );
        return M("house_log")->add($rental);
    }

    private function fn_GenerateGzfNo(){
        $data = array("time"=>date("Y-m-d H:i:s"));
        $no = M("gzf_no")->add($data);
        return "G".$no;
    }

    private function fn_MarkHouseOccupied($data, $zujin, $index){
        $houseData = array(
            "rzdate"=> $zujin['year']."/".$zujin['mstart']."/01",
            "state" => "租赁中",
            "zhname" => $data['name'],
            "zhidno" => $data['idno'],
            "zhname2" => $data['name2'],
            "zhidno2" => $data['idno2'],
            "jtnum" => $data['resident_num'],
            "dbnum" => $data['dibaork'],
            "dibaohm" => $data['dibaohm'],
            "phone" => $data['phone'],
            "yw_no"=> $data['no'],
            "contact_no"=> "HT".$data["no"],
            "utime"=> time(),
        );
        $res = M("house")->where(array("name"=>$data["house_no"]))->save($houseData);
        if(!$res){
            $this->error("行：".($index+2).",房源状态更新失败");
        }
    }

    private function fn_UpdateLzfApply($data, $index){
        $info = array(
            "community" => $data['house_comm'],
            "house_no" => $data['house_no'],
            "house_addr" => $data['house_addr'],
            "contact_no" => "HT".$data['no'],
        );
        $res = M("lzf")->where(array("no"=>$data['no']))->save($info);
        if(!$res){
            $this->error("行：".($index+2).",房源信息更新失败");
        }
    }

    private function fn_UpdateGzfApply($data, $index){
        $info = array(
            "community" => $data['house_comm'],
            "house_no" => $data['house_no'],
            "house_addr" => $data['house_addr'],
            "contact_no" => "HT".$data['no'],
        );
        $res = M("gzf")->where(array("no"=>$data['no']))->save($info);
        if(!$res){
            $this->error("行：".($index+2).",房源信息更新失败");
        }
    }

    private function fn_FormatZujin($data){
        $zj = array();
        if(floatval($data['2015zj'])>0){
            $month = explode("-", substr($data['2015yf'], 5));
            if(count($month)==1){
                $month[1] = '12';
            }
            $zj[] = array(
                "year" => "2015",
                "mstart" => $month[0],
                "mend" => $month[1],
                "total" => floatval($data['2015zj']),
            );
        }
        if(floatval($data['2016zj'])>0){
            $month = explode("-", substr($data['2016yf'], 5));
            if(count($month)==1){
                $month[1] = '12';
            }
            $zj[] = array(
                "year" => "2016",
                "mstart" => $month[0],
                "mend" => $month[1],
                "total" => floatval($data['2016zj']),
            );
        }
        if(floatval($data['2017zj'])>0){
            $month = explode("-", substr($data['2017yf'], 5));
            if(count($month)==1){
                $month[1] = '12';
            }
            $zj[] = array(
                "year" => "2017",
                "mstart" => $month[0],
                "mend" => $month[1],
                "total" => floatval($data['2017zj']),
            );
        }
        return $zj;
    }

    private function action_ImportRental($data, $zujin, $index, $type){
        if(count($zujin)>1){
            for($i=0; $i<count($zujin); $i++){
                $this->fn_PayRental($data, $zujin[$i], $index, $type);
            }
        }
    }

    private function fn_GeneratePaymentsNo(){
        $data = array("time"=>date("Y-m-d H:i:s"));
        $no = M("payments_no")->add($data);
        return "P".$no;
    }

    private function fn_PayRental($data, $zujin, $index, $type){
        //todo
        $pay = array(
            "name" => $this->fn_GeneratePaymentsNo(),
            "ptype" => $type."租金",
            "contact_no" => "HT".$data['no'],
            "community" => $data['house_comm'],
            "house_no" => $data['house_no'],
            "house_addr" => $data['house_addr'],
            "yw_no" => $data['no'],
            "amount" => $zujin['total'],
            "year" => $zujin['year'],
            "month_start" => $zujin['mstart'],
            "month_end" => $zujin['mend'],
            "type" => "收", //收，付
            "payer" => $data['name'],
            "payer_idno" => $data['idno'],
            "pdate" => $zujin['year']."/".$zujin['mstart']."/01",
            "remarks" => "初始化旧数据",
            "state" => "已确认",
            "cuser" => session("username"),
            "ctime" => time()
        );
        $res = M("payments")->add($pay);
        if(!$res){
            $this->error("行：".($index+2).", ".$zujin['year']."租金缴纳失败");
        }
    }

    private function action_ImportContact($data, $zujin, $index, $type){
        $contact = array(
            "no" => "HT".$data['no'],
            "ywno" => $data['no'],
            "community" => $data['house_comm'],
            "fwbh" => $data['house_no'],
            "fwdz" => $data['house_addr'],
            "size" => $data['house_size'],
            "zj" => $data['zj'],
            "mzj" => $data['zj'],
            "derate_money" => 0,
            "derate_type" => '无租金减免',
            "state" => "已签订",
            "type" => $type,
            "dibaork" => $data['dibaork'],
            "jiafang" => C("CONTACT_FAREN"),
            "yifang" => $data['name'],
            "jfjbr" => C("CONTACT_JINBAN"),
            "jffr" => C("CONTACT_FAREN"),
            "jfdz" => C("CONTACT_ADDR"),
            "jfdh" => C("CONTACT_PHONE"),

            "yfdw" => "",
            "yfdz" => "",
            "yfdh" => $data['phone'],
            "yfsfz" => $data['idno'],

            "yj" => C("CONTACT_YAJIN"),
            "total" => $zujin[0]['total'],
            "total2" => $zujin[0]['total'],
            "ksrq" => $zujin[0]['year']."/".$zujin[0]['mstart']."/01",
            "jsrq" => $zujin[0]['year']."/".$zujin[0]['mend']."/31",
            "remarks" => "旧数据导入",
            "cuser" => session("username"),
            "ctime" => $zujin[0]['year']."/".$zujin[0]['mstart']."/01",
        );
        $res = M("contact")->add($contact);
        if(!$res){
            //$this->error($data['house_comm']);
            $this->error(M("contact")->getLastSql());
            $this->error("行：".($index+2).",合同创建失败");
        }
    }

    private function action_ImportLottery($data, $index, $zujin){
        $batch = M("lottery_batch")->where(array("name"=>$data['batch']))->find();
        if(!$batch){
            $this->error("行：".($index+2).",摇号批次：".$data['batch']."不存在");
        }
        $lottery = array(
            "batch_id" => $batch['id'],
            "seq" => $data['seq'],
            "no" => $data['no'],
            "name" => $data['name'],
            "idno" => $data['idno'],
            "phone" => $data['phone'],
            "house_addr" => $data['house'],
            "contact_no" => "HT".$data['no'],
            //"state" => "已入住"
            "state" => "待入住"
        );
        if($zujin){
            $lottery['state'] = "已入住";
        }

        $res = M("lottery")->add($lottery);
        if(!$res){
            $this->error(M("lottery")->getLastSql());
            $this->error("行：".($index+2).",摇号数据创建失败");
        }
    }

    private function action_GzfImportApply($data, $zujin, $index){
        $marriage = $this->fn_GetMarriage($data["name2"]);
        $apply = array(
            "no" => $data['no'],
            "name" => $data["name"],
            "idno" => $data["idno"],
            "gender" => $this->fn_GetGenderByIdno($data["idno"]),
            "phone" => $data["phone"],
            "resident_num" => intval($data["resident_num"]),
            "dibaork" => intval($data["dibaork"]),
            "marriage" => $marriage,
            "area_id" => 1,  //所在社区和党委口
            "stime" => strtotime($zujin[0]['year']."/".$zujin[0]['mstart']."/01"),
            "state" => "done",
        );
        $res = M("gzf")->add($apply);
        if(!$res){
            $this->error(M("gzf")->getLastSql());
            $this->error("行：".($index+2).",创建公租房申请失败");
        }

        if($marriage=='已婚'){
            $family = array(
                "gzf_no" => $apply['no'],
                "name" => $data["name2"],
                "idno" => $data["idno2"],
                "phone" => $data["phone"],
                "gender" => $this->fn_GetGenderByIdno($data["idno2"]),
                "relation" => "配偶",
            );
            $res = M("gzf_family")->add($family);
            if(!$res){
                $this->error("行：".($index+2)."添加家庭成员信息失败");
            }
        }
    }

    private function action_LzfImportApply($data, $zujin, $index){
        $marriage = $this->fn_GetMarriage($data["name2"]);
        $apply = array(
            "no" => $data['no'],
            "name" => $data["name"],
            "idno" => $data["idno"],
            "gender" => $this->fn_GetGenderByIdno($data["idno"]),
            "phone" => $data["phone"],
            "dibao" => "是",
            "dibaohm" => $data["dibaohm"],
            "resident_num" => intval($data["resident_num"]),
            "dibaork" => intval($data["dibaork"]),
            "marriage" => $marriage,
            "attr" => '低保',     //家庭属性
            "hujiqk" => '家庭成员身份证',     //家庭属性
            "area_id" => 1,  //所在社区和党委口
            "stime" => strtotime($zujin[0]['year']."/".$zujin[0]['mstart']."/01"),
            "state" => "done",
        );
        $res = M("lzf")->add($apply);
        if(!$res){
            $this->error(M("lzf")->getLastSql());
            $this->error("行：".($index+2).",创建廉租房申请失败");
        }

        if($marriage=='已婚'){
            $family = array(
                "lzf_no" => $apply['no'],
                "name" => $data["name2"],
                "idno" => $data["idno2"],
                "phone" => $data["phone"],
                "gender" => $this->fn_GetGenderByIdno($data["idno2"]),
                "relation" => "配偶",
            );
            $res = M("lzf_family")->add($family);
            if(!$res){
                $this->error("行：".($index+2)."添加家庭成员信息失败");
            }
        }
    }

    public function fn_GetGenderByIdno($idno){
        $tag = substr($idno, 16, 1);
        if($tag%2=='1'){
            return "男";
        }else if($tag%2==0){
            return "女";
        }
        return null;
    }

    private function fn_GetMarriage($name){
        $marriage = '已婚';
        if($name=='丧偶'||$name=='已亡'){
            $marriage = '丧偶';
        }else if($name=='离婚'||$name=='离异'){
            $marriage = '离婚';
        }else if($name=='未婚' || $name==""){
            $marriage = '未婚';
        }
        return $marriage;
    }

    private function fn_GenerateLzfNo(){
        $data = array("time"=>date("Y-m-d H:i:s"));
        $no = M("lzf_no")->add($data);
        return "L".$no;
    }

    public function fn_ImportTaizhangExcel($inputFileName, $fields){
        import("Common.ORG.Util.PHPExcel");
        import("Common.ORG.Util.PHPExcel.Writer.Excel5");
        import("Common.ORG.Util.PHPExcel.IOFactory.php");

        try { //  Read your Excel workbook
            $inputFileType = \PHPExcel_IOFactory::identify($inputFileName);
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($inputFileName);
        } catch(Exception $e) {
            die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
        }

        //  Get worksheet dimensions
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();

        //  Loop through each row of the worksheet in turn
        // 第3行开始读取数据
        $rows = array();
        for ($row = 3; $row <= $highestRow; $row++){
            $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
            $data = array();
            for($i=0; $i<count($fields); $i++){
            //for($i=0; $i<count($rowData[0]); $i++){
                $data[$fields[$i]] = $rowData[0][$i];
            }
            if($data[$fields[0]] || $data[$fields[1]]){ //如果第一列、第二列的值为空，则认为该行为空行
                array_push($rows, $data);
            }
        }
        return $rows;
    }

    /**
     * 单位信息维护 -> formview
     */
    public function detail(){
        //读取单位信息
        $dataId = I("get.id");
        $user = M("user")->where(array("id"=>$dataId))->find();
        $this->assign("user", $user);

        //查询条件
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $pageInfo = $this->fn_GetPageInfo($where);

        //页面信息
        $offset = intval(I("get.offset"));
        $nearby = $this->fn_FindNearbyItems($where, $order, $offset);
        $page = array_merge($pageInfo, $nearby);
        $this->assign("page", $page);

        //company相关
        $company = $this->fn_GetCompany();
        $this->assign("company", $company);
        $company = $this->fn_GetCompany2();
        $this->assign("companyOptions", json_encode($company));

        //role相关
        $role = $this->fn_GetRole();
        $this->assign("role", $role);
        $role = $this->fn_GetRole2();
        $this->assign("roleOptions", json_encode($role));

        // 设置上下文信息
        $context = $this->fn_GenerateContext($page);
        $this->assign("context", $context);

        $this->display();
    }

    /**
     * 单位信息维护 -> 新增
     */
    public function add(){
        if(IS_POST){    //添加公司信息
            //$this->error(I("post.disable"));
            $disable = I("post.disable")=="on"?1:0;
            $data = array(
                "username" => I("post.username"),
                "passwd" => I("post.passwd"),
                "company_id" => I("post.company_id"),
                "role_id" => I("post.role_id"),
                "disable" => $disable,
                "title" => I("post.title"),
                "phone" => I("post.phone"),
                "cuser" => session("username"),
                "ctime" => time(),
            );
            $dataId = M("user")->add($data);
            if($dataId){
                header("Location:/admin/user/detail?id=".$dataId);
            }else{
                $this->error("系统错误，创建用户失败");
            }
        }

        //复制信息时处理流程
        if(I("get.id") && I("get.action"=="copy")){
            $user = M("user")->where(array("id"=>I("get.id")))->find();
            $this->assign("user", $user);
        }

        //company相关
        $company = $this->fn_GetCompany2();
        $this->assign("company", $company);

        //role相关
        $role = $this->fn_GetRole2();
        $this->assign("role", $role);

        $this->display();
    }

    /**
     * 修改个人资料
     */
    public function updateProfile(){

        $username = session("username");
        $where = array("username"=>$username);
        if(IS_POST){
            $data = array(
                "title" => I("post.title"),
                "phone" => I("post.phone"),
            );
            M("user")->where($where)->save($data);
            $this->success("资料修改成功");
        }

        //读取单位信息
        $user = M("user")->where($where)->find();
        $this->assign("user", $user);

        //company相关
        $company = $this->fn_GetCompany2();
        $this->assign("company", $company);

        //role相关
        $role = $this->fn_GetRole2();
        $this->assign("role", $role);

        $this->display();
    }

    /**
     * 修改登陆密码
     */
    public function passwd(){
        if(IS_POST){
            $username = I("post.username");
            if( I("post.newpwd") == I("post.passwd") ){
                $this->error("原密码与新密码不能相同");
            }
            if( I("post.newpwd2") != I("post.newpwd") ){
                $this->error("新密码两次输入不一致");
            }
            $where = array("username"=>$username);
            $data = array("passwd"=>I("post.newpwd"));
            $res = M("user")->where($where)->save($data);
            if($res){
                $this->success("修改成功");
            }else{
                $this->error("系统错误，修改失败");
            }
        }
        $this->assign("username", I("get.username"));
        $this->display();
    }

    /**
     * 修改登陆密码
     */
    public function updatePasswd(){
        if(IS_POST){
            $username = session("username");
            if(!$this->fn_IsPasswdMatched($username, I("post.passwd"))){
                $this->error("修改失败，原密码错误");
            }
            if( I("post.newpwd") == I("post.passwd") ){
                $this->error("原密码与新密码不能相同");
            }
            if( I("post.newpwd2") != I("post.newpwd") ){
                $this->error("新密码两次输入不一致");
            }
            $where = array("username"=>$username);
            $data = array("passwd"=>I("post.newpwd"));
            $res = M("user")->where($where)->save($data);
            if($res){
                $this->success("修改成功");
            }else{
                $this->error("系统错误，修改失败");
            }
        }
        $this->display();
    }

    /**
     * AJAX方法，在listview中进行批量删除信息
     */
    public function ajax_del(){

        $dataIds = I("post.info");
        if(count($dataIds)==0){
            $this->error("您还没有选中任何记录");
        }

        $map["id"] = array("in", $dataIds);
        $res = M("user")->where($map)->delete();
        if($res){
            $this->success("操作成功");
        }else{
            $this->error("系统错误");
        }
    }

    /**
     * AJAX方法，在formview中进行单条信息删除
     */
    public function ajax_del2(){
        //根据ID删除单位记录
        $id = I("post.id");
        $res = M("user")->where(array("id" => $id))->delete();
        if(!$res){
            $this->error("系统错误");
        }

        //分页信息
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $total = $this->fn_GetTotalItems($where);
        if($total==0){
            $this->success(null);
        }

        //计算下一条记录的offset
        $offset = intval(I("post.offset"));
        $offset = ($offset>=$total-1)?0:$offset;

        //获取下一记录的信息
        $nextItem = $this->fn_GetInfoByOffset($offset, $where, $order);
        $this->success($nextItem["id"]); //返回下一条记录的ID
    }

    /**
     * AJAX方法，通过ID来修改信息
     */
    public function ajax_UpdateInfoById(){
        $data = I("post.data");
        $dataId = I("post.id");
        $res = M("user")->where(array("id"=>$dataId))->save($data);
        if($res){
            $this->success("0k, 200");
        }else{
            $this->error("更新异常，请稍候再试");
        }
    }

    public function fn_IsPasswdMatched($username, $passwd){
        $where = array("username"=>$username, "passwd"=>$passwd);
        $res = M("user")->where($where)->find();
        return $res?true:false;
    }

    /**
     * 获取角色信息
     * @return mixed
     */
    public function fn_GetRole(){
        $result = array();
        $role = M("role")->order("id desc")->select();
        for($i=0; $i<count($role); $i++){
            $result[$role[$i]["id"]] = $role[$i]["name"]."(".$role[$i]["code"].")";
        }
        return $result;
    }

    /**
     * 返回list格式的角色信息
     * @return mixed
     */
    public function fn_GetRole2(){
        $role = M("role")->order("id desc")->select();
        foreach($role as $key => $value){
            $role[$key]['name'] = $role[$key]["name"]."(".$role[$key]["code"].")";
        }
        return $role;
    }

    /**
     * 获取政务分类信息  array
     * @return mixed
     */
    public function fn_GetCategory(){
        return M("affairscategory")->where(array("active"=>1))->order("seq desc")->select();
    }

    /**
     * 获取政务分类信息2 key => value
     * @return mixed
     */
    public function fn_GetCategory2(){
        $result = array();
        $category = M("affairscategory")->where(array("active"=>1))->order("seq desc")->select();
        for($i=0; $i<count($category); $i++){
            $result[$category[$i]["id"]] = $category[$i]["name"];
        }
        return $result;
    }

    /**
     * 获取单位信息
     * @return mixed
     */
    public function fn_GetCompany(){
        $result = array();
        $role = M("company")->order("id desc")->select();
        for($i=0; $i<count($role); $i++){
            $result[$role[$i]["id"]] = $role[$i]["name"];
        }
        return $result;
    }

    /**
     * 返回list格式单位信息
     * @return mixed
     */
    public function fn_GetCompany2(){
        return M("company")->order("id desc")->select();
    }

    /**
     *  辅助方法，通过$_POST的值来生成where查询条件
     */
    private function fn_GenerateWhereClause(){
        if(!I("request.value")){
            return array();
        }
        $where = array();
        if(I("request.field")=="role_id"){ //多表查询处理
            $cateIds = $this->fn_SelectCategoryByName(I("request.value"));
            $where[I("request.field")] = array("in", $cateIds);
        }else if(I("request.field")=="company_id"){ //多表查询处理
            $cateIds = $this->fn_SelectCategoryByName(I("request.value"));
            $where[I("request.field")] = array("in", $cateIds);
        }else{
            $where[I("request.field")] = array("like", "%".I("request.value")."%");
        }
        return $where;
    }

    private function fn_SelectCategoryByName($name){
        $where["name"] =  array("like", "%".$name."%");
        $result = M("affairscategory")->where($where)->field("id")->select();
        $cateIds = array();
        for($i=0; $i<count($result); $i++){
            array_push($cateIds, $result[$i]["id"]);
        }
        return $cateIds;
    }

    /**
     *  辅助方法，通过$_POST的值来生成order by子句
     */
    private function fn_GenerateOrderBy(){
        $order = "id asc";
        if(I("request.order_field") && I("request.order_sort")){
            $order = I("request.order_field") . " " . I("request.order_sort");
        }
        return $order;
    }

    /**
     *  辅助方法，通过$_POST的值来生成Filter (listview)
     */
    private function fn_GenerateFilter(){
        if(IS_POST){
            return array(
                "page" => I("post.page"),
                "field" => I("post.field"),
                "value" => I("post.value"),
                "order_field" => I("post.order_field"),
                "order_sort" => I("post.order_sort"),
            );
        }
        return array(
            "page" => 1,
            "order_field" => "id",
            "order_sort" => "asc",
        );
    }

    /**
     * 辅助方法，通过$_POST的值来生成Context (formvier)
     * @return array
     */
    private function fn_GenerateContext($page){
        return array(
            "id" => I("request.id"),
            "field" => I("request.field"),
            "value" => I("request.value"),
            "order_field" => I("request.order_field"),
            "order_sort" => I("request.order_sort"),
            "page" => I("request.page"),
            "offset" => I("request.offset"),
            "index" => I("get.offset")-($page["curPage"]-1)*$page["num"]+1
        );
    }

    /**
     * 辅助方法，通过where,order,offset来查询信息
     * @param $offset
     * @param $where
     * @param $order
     * @return mixed
     */
    private function fn_GetInfoByOffset($offset, $where, $order){
        $limit = $offset.",1";
        $res =  M("user")->field("id,title")->where($where)->order($order)->limit($limit)->select();
        if($res){
            return $res[0];
        }
        return array();
    }

    /**
     * 辅助方法，通过where, curpage, num来生成分页信息
     * @param $where
     * @param int $curPage
     * @param int $num
     * @return array
     */
    private function fn_GetPageInfo($where, $curPage=1, $num=15){
        $total = M("user")->where($where)->count();
        $totalPage = ceil($total/$num);
        $nextPage = $curPage==$totalPage?1:($curPage+1);
        $prevPage = $curPage==1?$totalPage:($curPage-1);
        $to = $curPage*$num;
        $res = array(
            "total" => $total,
            "num" => $num,
            "from" => (($curPage-1)*$num+1),
            "to" => $to>$total?$total:$to,
            "curPage" => $curPage,
            "nextPage" => $nextPage,
            "prevPage" => $prevPage
        );
        return $res;
    }

    /**
     * 辅助方法，通过where来统计总的信息数量
     * @param array $where
     * @return mixed
     */
    public function fn_GetTotalItems($where=array()){
        return M("user")->where($where)->count();
    }

    /**
     * 辅助方法，通过where, order, offset查询相邻两条数据
     * @param $where
     * @param $offset
     */
    public function fn_FindNearbyItems($where, $order, $offset){
        $total = M("user")->where($where)->count();
        $prevOffset = $offset>0?$offset-1:$total-1;
        $nextOffset = $offset>=$total-1?0:$offset+1;
        $prevItem = $this->fn_GetInfoByOffset($prevOffset, $where, $order);
        $nextItem = $this->fn_GetInfoByOffset($nextOffset, $where, $order);
        return array(
            "prev" => array("id"=>$prevItem["id"],"offset"=>$prevOffset),
            "next" => array("id"=>$nextItem["id"],"offset"=>$nextOffset),
        );
    }

}